package org.qing.freepx.controller;

import org.qing.freepx.entity.IPProxy;
import org.qing.freepx.service.IPProxyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * Mono 和 Flux 适用于两个场景，即： Mono：实现发布者，并返回 0 或 1 个元素，即单对象。 Flux：实现发布者，并返回 N 个元素，即
 * List 列表对象。 有人会问，这为啥不直接返回对象，比如返回 City/Long/List。 原因是，直接使用 Flux 和 Mono
 * 是非阻塞写法，相当于回调方式。 利用函数式可以减少了回调，因此会看不到相关接口。这恰恰是 WebFlux 的好处：集合了非阻塞 + 异步
 * 
 * @author qing
 *
 */
@RestController
public class ProxyIPController {

	@Autowired
	private IPProxyService iPProxyService;

	@RequestMapping(value = "test", method = RequestMethod.GET, produces = { "application/json" })
	public Mono<String> testMono(ServerRequest request,ServerResponse response) {
		return iPProxyService.test();
	}

	@RequestMapping(value = "addIPProxy", method = RequestMethod.POST, produces = { "application/json" })
	public Flux<IPProxy> add(@RequestBody Flux<IPProxy> iPProxys) {
		return iPProxyService.createOrUpdate(iPProxys);
	}

	@RequestMapping(value = "getIPProxy/{ip}", method = RequestMethod.GET, produces = { "application/json" })
	public Mono<IPProxy> getIPProxy(@PathVariable String ip) {
		return iPProxyService.getIPProxyBeanById(ip);
	}
	
	@RequestMapping(value = "getIPProxyList", method = RequestMethod.GET, produces = { "application/json" })
	public Flux<IPProxy> getIPProxy() {
		return iPProxyService.getAllIPProxyBeanList();
	}

	@RequestMapping(value = "deleteIPProxy/{ip}", method = RequestMethod.POST, produces = { "application/json" })
	public Mono<IPProxy> delete(@PathVariable String ip) {
		return iPProxyService.deleteById(ip);
	}

}
